'use client'
import { useState, useEffect } from 'react'
import { storage } from '@/services/storage'
import PageContainer from '@/components/PageContainer'
import StudyStats from '@/components/stats/StudyStats'

export default function StatsPage() {
  const [stats, setStats] = useState(null)

  useEffect(() => {
    const calculateStats = () => {
      const cards = storage.getCards()
      const decks = storage.getDecks() 
      const now = new Date()
      
      // 计算基础统计数据
      const totalReviews = cards.reduce((sum, card) => sum + (card.reviews || 0), 0)
      const totalCorrect = cards.reduce((sum, card) => sum + (card.correct || 0), 0)
      const dueToday = cards.filter(card => new Date(card.nextReview) <= now).length

      // 计算近7天的学习数据
      const dailyStats = []
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now)
        date.setDate(date.getDate() - i)
        date.setHours(0, 0, 0, 0)
        
        const nextDate = new Date(date)
        nextDate.setDate(date.getDate() + 1)

        const dayCards = cards.filter(card => {
          const modified = new Date(card.modified)
          return modified >= date && modified < nextDate
        })

        dailyStats.push({
          date: date.toLocaleDateString(),
          reviews: dayCards.length,
          correct: dayCards.filter(card => card.correct > card.incorrect).length
        })
      }

      const deckStats = decks.map(deck => {
        const deckCards = cards.filter(card => card.deck === deck.id)
        const reviews = deckCards.reduce((sum, card) => sum + (card.reviews || 0), 0)
        const correct = deckCards.reduce((sum, card) => sum + (card.correct || 0), 0)
        const avgInterval = deckCards.reduce((sum, card) => sum + (card.interval || 0), 0) / (deckCards.length || 1)
        const lastReview = Math.max(...deckCards.map(card => new Date(card.modified || 0)))
      
        return {
          id: deck.id,
          name: deck.name,
          cardCount: deckCards.length,
          reviews,
          correct,
          avgInterval,
          lastReview
        }
      })
      
      // 添加时段统计
      const hourlyStats = Array.from({ length: 24 }, (_, i) => ({
        hour: i,
        count: cards.filter(card => new Date(card.modified).getHours() === i).length
      }))
      
      // 添加记忆保持率统计
      const retentionStats = Array.from({ length: 30 }, (_, i) => {
        const interval = i + 1
        const cardsWithInterval = cards.filter(card => card.interval === interval)
        const retention = cardsWithInterval.length > 0
          ? cardsWithInterval.filter(card => card.correct > card.incorrect).length / cardsWithInterval.length
          : 0
      
        return {
          interval,
          retention: retention * 100
        }
      })
      
      setStats({
        totalReviews,
        totalCorrect,
        dueToday,
        totalCards: cards.length,
        dailyStats,
        deckStats,
        hourlyStats,
        retentionStats
      })
    }

    calculateStats()
  }, [])

  if (!stats) return null

  return (
    <PageContainer>
      <div className="max-w-6xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">学习统计</h1>
          <p className="text-gray-600 mt-2">查看您的学习进度和效果</p>
        </div>

        <StudyStats stats={stats} />
      </div>
    </PageContainer>
  )
}